package com.ligongmusic.activity;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.logging.Logger;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.text.Layout;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.ligongmusic.R;
import com.ligongmusic.domain.DynamicDomain;
import com.ligongmusic.domain.LrcRow;
import com.ligongmusic.domain.MusicInfo;
import com.ligongmusic.impl.DefaultLrcBuilder;
import com.ligongmusic.inter.ILrcBuilder;
import com.ligongmusic.inter.ILrcViewListener;
import com.ligongmusic.service.MusicOnlineService;
import com.ligongmusic.util.GlobalParams;
import com.ligongmusic.util.LoggerUtils;
import com.ligongmusic.util.LrcUtil;
import com.ligongmusic.util.NetWorkUtils;
import com.ligongmusic.util.StringUtils;
import com.ligongmusic.view.LrcView;
import com.ligongmusic.view.TopManager;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.w3c.dom.Text;

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public class MusicActivity extends Activity implements OnClickListener {
//	private List<MusicInfo> mMusics;
	private ImageView nextPlayer;
	private ImageView beforePlayer;
	private ImageView player;
	public static int DYNAMIC = 0x1;
//	private int from;// 来源Activity
	private int playerStatus;
	public static int MUSIC_LIST = 0x2;
	public static int MUSIC_NEW = 0x3;
	public static int MUSIC_CONTINUE = 0x4;
	private SeekBar mSeekBar;
	private TextView tv_max_time, tv_current_time;
	private LrcView mLrcView;
	private LrcView mFullLrcView;
	// 当前播放时间 
	private Long currentTime = 0l;
	//更新歌词的频率，每秒更新一次
    private int mPalyTimerDuration = 1000;
    //更新歌词的定时器
    private Timer mTimer;
    //更新歌词的定时任务
    private TimerTask mTask;
//	private ListView mListView;
	private Messenger mMessenger;
	private int current = 0;
	private boolean isSeek = true;// 滑动时不更新进度条
	private TextView tvPrise;
	private DynamicDomain music;
	private TextView commentsNum;
	private ImageView loading;
	//	private RelativeLayout loadStatus;
//	private TextView loadProgress;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.music);
//		mMusics = getIntent().getParcelableArrayListExtra("music");
		music = (DynamicDomain) getIntent().getSerializableExtra("info");
//		from = getIntent().getIntExtra("from", -1);
		playerStatus = getIntent().getIntExtra("player", -1);
		initView();
	}

	private Handler mHandler = new Handler(){
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MusicOnlineService.CURRENT_TIME_TYPE:
				// 当前播放时长
//				LoggerUtils.getLog(MusicActivity.class).error(msg.obj.toString());
				currentTime = (long) msg.arg1;
				if(isSeek){
					loading.setVisibility(View.GONE);
					setAlphaAnimotion();
					boolean isPlay = (Boolean) msg.obj;
					if(isPlay){
						player.setBackground(getResources().getDrawable(R.drawable.pause_music));
						player.setTag("pause");
					}else{
						player.setBackground(getResources().getDrawable(R.drawable.play_music));
						player.setTag("play");
					}
					mSeekBar.setProgress(msg.arg1);
					mSeekBar.setMax(msg.arg2);
					tv_max_time.setText(StringUtils.getMusicMax(msg.arg2));
					tv_current_time.setText(StringUtils.getMusicMax(msg.arg1));
				}
				break;
			case MusicOnlineService.PLAYER_NEXT:
				// 播放下一首 ，改变ListView选中位置
//				current ++ ;
//				mListView.setSelection(current);
				playerNext();
				break;
			case MusicOnlineService.SEEK_RESUME:
				// 未准备就绪，进度条不改变
				mSeekBar.setProgress(0);// 从0开始计数
				tv_current_time.setText("00:00");
				break;
			case MusicOnlineService.CHANGE_SEEK:
				currentTime = (long) msg.arg1;
				// 改变歌词显示位置
				mLrcView.seekLrcToTime(msg.arg1);
				mFullLrcView.seekLrcToTime(msg.arg1);
				// 改变SeekBar
				mSeekBar.setProgress(msg.arg1);
				tv_current_time.setText(StringUtils.getMusicMax(msg.arg1));
				break;
			case MusicOnlineService.LOAD_ING:
				// 缓冲中
//				loadStatus.setVisibility(View.VISIBLE);
				Log.e("LoggerUtils", "handleMessage: success");
				loading.setVisibility(View.VISIBLE);
				setAlphaAnimotion1();
				break;
			case MusicOnlineService.LOAD_SUCCESS:
				Log.e("LoggerUtils", "handleMessage: success");
				// 缓冲完成
				loading.setVisibility(View.GONE);
				setAlphaAnimotion();
//				loadStatus.setVisibility(View.GONE);
				break;
			}
		};
	};
	private ImageView packUp;


	/**
	 * 下一首
	 */
	private void playerNext(){
//		if(current == mMusics.size() - 1)
//			current = 0;
//		else
//			current ++ ;
		startPlayer();
	}

	private void startPlayer(){
		findLrc();
//		LoggerUtils.getLog(MusicActivity.class).error("当前播放" + mMusics.get(current).getFileName());
		isSeek = true;
		mSeekBar.setProgress(0);// 从0开始计数
		Intent intent = new Intent(MusicActivity.this, MusicOnlineService.class);
		intent.putExtra("musicName", GlobalParams.MUSIC_URL + music.getSong_src());
		intent.putExtra("status", MusicOnlineService.START_MUSIC);
		startService(intent);
	}

	/**
	 * 暂停
	 */
	private void playerPause(){
		Intent intent = new Intent(MusicActivity.this, MusicOnlineService.class);
		intent.putExtra("status", MusicOnlineService.PAUSE_MUSIC);
		startService(intent);
	}

	/**
	 * 播放
	 */
	private void player(){
//		LoggerUtils.getLog(MusicActivity.class).error("当前播放" + mMusics.get(current).getFileName());
		Intent intent = new Intent(MusicActivity.this, MusicOnlineService.class);
		intent.putExtra("musicName", GlobalParams.MUSIC_URL + music.getSong_src());
		intent.putExtra("status", MusicOnlineService.CONTINUE_MUSIC);
		startService(intent);
	}

	/**
	 * 通过进度条改变播放位置
	 */
	private void seekToPlayer(int time){
		Intent intent = new Intent(MusicActivity.this, MusicOnlineService.class);
		intent.putExtra("status", MusicOnlineService.SEEK_TO_PROGRESS);
		intent.putExtra("seek_time", time);
		startService(intent);
	}

	/**
	 * 上一曲
	 */
	private void playerBefore(){
//		if(current == 0)
//			current = mMusics.size() - 1;
//		else
//			current -- ;
		startPlayer();
	}

	private void setAnimotion(){
		RotateAnimation animation = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
		animation.setDuration(1000);
		animation.setRepeatCount(Integer.MAX_VALUE);
		loading.clearAnimation();
		loading.setAnimation(animation);
	}

	private void setAlphaAnimotion(){
		AlphaAnimation a = new AlphaAnimation(1f, 0f);
		a.setFillAfter(true);
		loading.clearAnimation();
		loading.setAnimation(a);
	}
	private void setAlphaAnimotion1(){
		AlphaAnimation a = new AlphaAnimation(0f, 1f);
		a.setFillAfter(true);
		loading.clearAnimation();
		loading.setAnimation(a);
	}

	private void initView() {
//		mListView = (ListView) findViewById(R.id.list);
		TopManager.getTopManager(MusicActivity.this).showTop(true, music.getSong_name() + "", new OnClickListener() {
			@Override
			public void onClick(View v) {
				setResult(0x5);
				finish();
			}
		});
		loading = (ImageView) findViewById(R.id.iv_loading);
		setAnimotion();

		ImageLoader.getInstance().displayImage(GlobalParams.IMAGE_URL + music.getCover(), ((ImageView)findViewById(R.id.music_icon)));
//		LoggerUtils.getLog(MusicActivity.class).error(GlobalParams.IMAGE_URL + music.getCover());
//		loadStatus = (RelativeLayout) findViewById(R.id.ll_load);
		Log.e("LoggerUtils", GlobalParams.IMAGE_URL + music.getCover());
//		loadProgress = (TextView) findViewById(R.id.tv_progress);
		mSeekBar = (SeekBar) findViewById(R.id.seek_bar);
		mLrcView = (LrcView) findViewById(R.id.lrc_view);
		mFullLrcView = (LrcView) findViewById(R.id.full_lrc_view);
//		mFullLrcView.
		tv_max_time = (TextView) findViewById(R.id.tv_max_time);
		tv_current_time = (TextView) findViewById(R.id.tv_current_time);
		tvPrise = (TextView)findViewById(R.id.prise_num);
		((ImageView)findViewById(R.id.iv_share)).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				shareApp(GlobalParams.MUSIC_URL + music.getSong_src());
			}
		});
		Drawable drawable = null;
		if(!GlobalParams.isLogin || music.getStatus() == 0)// 未赞
			drawable = getResources().getDrawable(R.drawable.music_prise);
		else
			drawable = getResources().getDrawable(R.drawable.small_praise);
		drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
		tvPrise.setCompoundDrawables(drawable, null, null, null);
		tvPrise.setText("赞（" + music.getLike_count() +  "）");
		tvPrise.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (!GlobalParams.isLogin) {
					Toast.makeText(getApplicationContext(), "请先登录再操作", Toast.LENGTH_SHORT).show();
					return;
				}
				praise(music.getSong_id(), music.getStatus());
			}
		});
		commentsNum = (TextView)findViewById(R.id.comments_num);
		commentsNum.setText("评论（" + music.getComment_count() +  "）");
		commentsNum.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {// TODO 评论
				if (!GlobalParams.isLogin) {
					Toast.makeText(getApplicationContext(), "请先登录再操作", Toast.LENGTH_SHORT).show();
					return;
				}
				Intent intent = new Intent(MusicActivity.this, CommentsActivity.class);
				intent.putExtra("comments", music);
				startActivityForResult(intent, 0x6);
			}
		});
		packUp = (ImageView) findViewById(R.id.iv_pack_up);
		mSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			// 进度条停止拖动的时候调用
			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				// 处理播放位置
				isSeek = true;
				seekToPlayer(seekBar.getProgress());
			}
			// 拖动进度条开始拖动的时候调用
			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				isSeek = false;
			}
			// 拖动进度条进度改变的时候调用
			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				tv_current_time.setText(StringUtils.getMusicMax(progress));

			}
		});
		// 全屏歌词
		((ImageView)findViewById(R.id.iv_lrc_detail)).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mFullLrcView.setVisibility(View.VISIBLE);
				packUp.setVisibility(View.VISIBLE);
			}
		});
		packUp.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mFullLrcView.setVisibility(View.GONE);
				packUp.setVisibility(View.GONE);
			}
		});
		nextPlayer = (ImageView) findViewById(R.id.iv_right);
		beforePlayer = (ImageView) findViewById(R.id.iv_left);
		player = (ImageView) findViewById(R.id.iv_play);

		beforePlayer.setOnClickListener(this);
		nextPlayer.setOnClickListener(this);
		player.setOnClickListener(this);

//		mMusics = AudioUtils.getMusicList(this);
		mMessenger = new Messenger(mHandler);
		Intent intent = new Intent(MusicActivity.this, MusicOnlineService.class);
		intent.putExtra("messenger", mMessenger);
		startService(intent);
		if(playerStatus == MUSIC_NEW)// 如果进入来源是动态界面并且是新的音乐，则新播放
			startPlayer();
		else
			findLrc();
//		setMusicAdapter();
	}

	//分享文字
	public void shareApp(String url) {
		Intent shareIntent = new Intent();
		shareIntent.setAction(Intent.ACTION_SEND);
		shareIntent.putExtra(Intent.EXTRA_TEXT, url);
		shareIntent.setType("text/plain");
		//设置分享列表的标题，并且每次都显示分享列表
		startActivity(Intent.createChooser(shareIntent, "分享到"));

	}

	/**
	 * 查找歌词
	 */
	private void findLrc(){
		if (StringUtils.isEmpty(music.getLyric())) {
			mLrcView.setLoadingTipText("暂无歌词");
			return;
		}
		String filePath = getFilesDir() + "/lgMusic/" + music.getLyric();
		LoggerUtils.getLog(MusicActivity.class).error(filePath);
//		File file = new File(filePath);
//		File file = new File(Environment.getExternalStorageDirectory() + "/lgMusic/" + mMusics.get(current).getFileName() + ".lrc");
//		if(file.exists()) {
//        	downSuccess(Environment.getExternalStorageDirectory() + "/lgMusic/acc.lrc");
//			downSuccess(filePath);
//        	downSuccess(Environment.getExternalStorageDirectory() + "/lgMusic/" + mMusics.get(current).getFileName() + ".lrc");
//		}else
		downLoadLrc(filePath);
	}
	private void downLoadLrc(String filePath){
		NetWorkUtils.downLoadFile(GlobalParams.MUSIC_URL + music.getLyric(), getFilesDir() + "/lgMusic/",/*getFilesDir() *//*Environment.getExternalStorageDirectory()*//* + "/lgMusic/", mMusics.get(current).getFileLrc()*/filePath, new NetWorkUtils.NetWorkCallBack() {
			@Override
			public void success(String result) {
				LoggerUtils.getLog(MusicActivity.class).error("download_success:" + result);
				downSuccess(result);
			}
			@Override
			public void error(String message) {
				mLrcView.setLoadingTipText("暂无歌词");
				LoggerUtils.getLog(MusicActivity.class).error("download_error:" + message);
			}
			@Override
			public void error() {
				mLrcView.setLoadingTipText("暂无歌词");
				LoggerUtils.getLog(MusicActivity.class).error("download_error:");
			}
		});
	}

	/**
	 * 歌词下载完成后调用
	 */
	private void downSuccess(final String result){
		new Thread(new Runnable() {
			@Override
			public void run() {
				//读取文件
				LoggerUtils.getLog(MusicActivity.class).error(getFilesDir() + "/lgMusic/" + music.getLyric());
				String lrc = LrcUtil.getFromAssets(getFilesDir() + "/lgMusic/" + music.getLyric());
				if (lrc == null) {
					// 当前缓存歌词不完整，重新下载
//					String filePath = getFilesDir() + "/lgMusic/" + music.getLyric();
					mLrcView.setLoadingTipText("暂无歌词");
//					downLoadLrc(filePath);
					return;
				}
				LoggerUtils.getLog(MusicActivity.class).error(lrc);
				//解析歌词构造器
				ILrcBuilder builder = new DefaultLrcBuilder();
				//解析歌词返回LrcRow集合
				final List<LrcRow> rows = builder.getLrcRows(lrc);
				if (rows == null || rows.size() == 0)
					return;
//				for (LrcRow r : rows) {
//					LoggerUtils.getLog(MusicActivity.class).error(r.toString());
//				}
				runOnUiThread(new Runnable() {
					@Override
					public void run() {

						//将得到的歌词集合传给mLrcView用来展示
						mLrcView.setLrc(rows);
						mFullLrcView.setLrc(rows);
						if(mTimer == null){
							mTimer = new Timer();
							mTask = new LrcTask();
							mTimer.scheduleAtFixedRate(mTask, 0, mPalyTimerDuration);
						}

						//设置自定义的LrcView上下拖动歌词时监听
						mLrcView.setListener(new ILrcViewListener() {
							//当歌词被用户上下拖动的时候回调该方法,从高亮的那一句歌词开始播放
							public void onLrcSeeked(int newPosition, LrcRow row) {
								seekToPlayer((int) row.time);
							}
						});
						mFullLrcView.setListener(new ILrcViewListener() {
							//当歌词被用户上下拖动的时候回调该方法,从高亮的那一句歌词开始播放
							public void onLrcSeeked(int newPosition, LrcRow row) {
								seekToPlayer((int) row.time);
							}
						});
					}
				});
			}
		}).start();

	}

//    Runnable mUpdateResults = new Runnable() {  
//        public void run() {  
//            lyric.invalidate(); // 更新视图  
//        }  
//    };  

	/**
     * 停止展示歌曲
     */
    public void stopLrcPlay(){
        if(mTimer != null){
            mTimer.cancel();
            mTimer = null;
        }
    }


	/**
	 * 点赞
	 */
	private void praise(int sid, final int exastatus){
		List<NameValuePair> pairs = new ArrayList<NameValuePair>();
		pairs.add(new BasicNameValuePair("songid", sid + ""));
		pairs.add(new BasicNameValuePair("loginname", GlobalParams.userName));
		pairs.add(new BasicNameValuePair("token", GlobalParams.token));
		NetWorkUtils.getRequest(pairs, GlobalParams.PRISE, new NetWorkUtils.NetWorkCallBack() {
			@Override
			public void success(String result) {
				LoggerUtils.getLog(MusicActivity.class).error(result);
				Drawable drawable = null;
				if(music.getStatus() == 0) {// 未赞
					music.setStatus(1);
					drawable = getResources().getDrawable(R.drawable.small_praise);
					music.setLike_count(music.getLike_count() + 1);
					tvPrise.setText("赞（" + music.getLike_count() +  "）");
				}else {
					music.setStatus(0);
					music.setLike_count(music.getLike_count() - 1);
					drawable = getResources().getDrawable(R.drawable.music_prise);
					tvPrise.setText("赞（" + music.getLike_count() +  "）");
				}
				drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
				tvPrise.setCompoundDrawables(drawable,null,null,null);
			}
			@Override
			public void error(String message) {
				LoggerUtils.getLog(MusicActivity.class).error(message);
			}
			@Override
			public void error() {
				// TODO Auto-generated method stub
			}
		});
	}


	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iv_right:
			playerNext();
			break;
		case R.id.iv_left:
			playerBefore();
			break;
		case R.id.iv_play:
//			if(player.getBackground() == getResources().getDrawable(R.drawable.play_music))
//				player.setBackground(getResources().getDrawable(R.drawable.pause_music));
//			else
//				player.setBackground(getResources().getDrawable(R.drawable.play_music));
			String tag = (String) player.getTag();
			if("play".equals(tag)){
				player.setBackgroundResource(R.drawable.pause_music);
				player.setTag("pause");
				player();
			}else{
				player.setBackgroundResource(R.drawable.play_music);
				player.setTag("play");
				playerPause();
			}
			break;

		default:
			break;
		}
	}

	/**
     * 展示歌曲的定时任务
     */
    class LrcTask extends TimerTask{
        @Override
        public void run() {
            //获取歌曲播放的位置
//            final long timePassed = mPlayer.getCurrentPosition();
            MusicActivity.this.runOnUiThread(new Runnable() {
                public void run() {
                    //滚动歌词
                    mLrcView.seekLrcToTime(currentTime);
                    mFullLrcView.seekLrcToTime(currentTime);
                }
            });

        }
    };

    /**
     * 筛选MP3
     */
    class MusicFilter implements FilenameFilter {
        public boolean accept(File dir, String filename) {
            return (filename.endsWith(".lrc"));
        }
    }

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK){
			setResult(0x5);
			finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
}
